package com.user.query.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.*;

public class JDBCUTILS {
    private static Properties pro;
    static {
        pro = new Properties();
        InputStream is = JDBCUTILS.class.getClassLoader().getResourceAsStream("jdbc2.properties");
        try {
            pro.load(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getProperty(String key) {
        return pro.getProperty(key);
    }

    public List<Object> executeSql(String sql) throws Exception {
        String driver = getProperty("jdbc.driver");
        String url = getProperty("jdbc.url");
        String user = getProperty("jdbc.user");
        String password = getProperty("jdbc.password");
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url, user, password);
        if (!conn.isClosed())
            System.out.println("Succeeded connecting to the Database!");
        else
            System.err.println("connect filed");
        // 获取所有表名
        Statement statement = conn.createStatement();
      ResultSet rs= statement.executeQuery(sql);
        List<Map<String,Object>> rawList = new ArrayList<Map<String,Object>>();
        rawList= getResultList(rs);
        System.out.println(rawList.get(0));
        return null;
    }
    /*
        * 解析ResultSet 表列数据
        */
    private Map<String,Object> getResultMap(ResultSet rs) throws SQLException {
        Map<String, Object> rawMap = new HashMap<String, Object>();
        ResultSetMetaData rsmd = rs.getMetaData(); // 表对象信息
        int count = rsmd.getColumnCount();          // 列数
        // 遍历之前需要调用 next()方法
        for (int i = 1; i <= count; i++) {
            String key = rsmd.getColumnLabel(i);
            System.out.println(rsmd.getColumnName(i));
            System.out.println("label--"+rsmd.getColumnLabel(i));
            Object value = rs.getObject(key);
            rawMap.put(key, value);
        }
        return rawMap;
    }
    private List<Map<String,Object>> getResultList(ResultSet rs) throws SQLException {
        List<Map<String,Object>> rawList = new ArrayList<Map<String,Object>>();
        while(rs.next()){
            Map<String, Object> rawMap = getResultMap(rs);
            rawList.add(rawMap);
        }
        return rawList;
    }
    public static void main(String[] args) throws  Exception {
        JDBCUTILS j=new JDBCUTILS();
        j.executeSql("select * from user");
    }
}
